import axios, {
	AxiosInstance,
	AxiosResponse
} from "axios"
import { ElMessage } from "element-plus";
import nProgress from "nprogress";
import { quitOut } from "./chore";
import axiosRetry from 'axios-retry'
export const BASE_URL =  "http://101.43.122.86:9001"
// export const BASE_URL =  "http://localhost:9001"
const axiosMain = axios.create({
	headers: {
		"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
	},
	baseURL: BASE_URL,
})
axiosRetry(axiosMain, {retries: 3})

axiosMain.interceptors.request.use(
	config => {
		config.headers['token'] = localStorage.getItem('token')
		nProgress.start()
		return config;
	},
	error => {
		nProgress.done()
		ElMessage({type:'error', message:'网络错误'})
		return Promise.reject(error);
	}
);
axiosMain.interceptors.response.use(
	response => {
		nProgress.done()
		if(response.data.authorizeNotOk){
			ElMessage({type: 'warning', message: '身份已过期，请重新登陆'})
			quitOut() // 写完路由的代码后，一定要强制刷新浏览器，否则浏览器无法同步变化
			window.location.reload()
		}
		if(response.data.tooFrequent){
			ElMessage({type: 'error', message: '请求过于频繁，请十秒后再试'})
		}
		return response;
	},
	error => {
		nProgress.done()
		ElMessage({type:'error', message:'网络错误'})
		return Promise.reject(error);
	}
);


// const axiosImg = axios.create({
// 	baseURL: "https://api.superbed.cn/upload",
// 	headers:{
// 		'Content-Type': 'multipart/form-config'
// 	}
// })
// axiosRetry(axiosImg, {retries: 3})
//
// axiosImg.interceptors.request.use(
// 	config => {
// 		nProgress.start()
// 		return config;
// 	},
// 	error => {
// 		nProgress.done()
// 		ElMessage({type:'error', message:'网络错误'})
// 		return Promise.reject(error);
// 	}
// );
//
// axiosImg.interceptors.response.use(
// 	response => {
// 		nProgress.done()
// 		return response;
// 	},
// 	error => {
// 		nProgress.done()
// 		ElMessage({type:'error', message:'网络错误'})
// 		return Promise.reject(error);
// 	}
// );



export class Http {
	axiosInstance: AxiosInstance
	constructor(ai: AxiosInstance) {
		this.axiosInstance = ai
	}
	public get < T = any, D = any > (url: string, params ? : D) {
		return this.axiosInstance.get < T, AxiosResponse < T > , any > (url, {params})
	}
	public post < T = any, D = any > (url: string, data?: D) {
		return this.axiosInstance.post < T, AxiosResponse < T > , D > (url, data)
	}
}

export const http = new Http(axiosMain)
// export const httpImg = new Http(axiosImg)
